/*
 * Copyright (C) 2009, Edmundo Albuquerque de Souza e Silva.
 *
 * This file may be distributed under the terms of the Q Public License
 * as defined by Trolltech AS of Norway and appearing in the file
 * LICENSE.QPL included in the packaging of this file.
 *
 * THIS FILE IS PROVIDED AS IS WITH NO WARRANTY OF ANY KIND, INCLUDING
 * THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
 * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
 * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
 * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
 * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

package com.lti.utils.synchronization;


public class SynchronizedObjectHolder<T>
{

	public SynchronizedObjectHolder()
	{
		super();
	}
	
	public SynchronizedObjectHolder(T value)
	{	setObject(value);
	}
	
	private T object;
	
	public synchronized void setObject(T value)
	{
		object = value;
		notifyAll();
		
	}
	
	public synchronized T getObject()
	{
		return object;
	}
	
	public synchronized void waitUntilNotNull() throws InterruptedException
	{	while (object == null)
		{
			wait();
		}
			
	}
	
	/**
	 * @return true if value is now non-null, false if timeout occurred
	 */
	public synchronized boolean waitUntilNotNull(int timeout) throws InterruptedException
	{	long start = System.currentTimeMillis();
		while (object == null)
		{	long now = System.currentTimeMillis();
			long diff = now - start;
			long wait = timeout - diff;
			if (wait <= 0)
				return false;
			wait(wait);
		}
		return true;
	
	}	
}
